package service

import (
	"RoccBlog/model"
	"RoccBlog/util/constant"
	"errors"
	"github.com/gin-gonic/gin"
	"strconv"
)

type BaseOperationService interface {
	Add(ctx *gin.Context, data any) error
	Remove(ctx *gin.Context, id int) error
	Modify(ctx *gin.Context, data any) error
	FindById(ctx *gin.Context, id int) (any, error)
	Find(ctx *gin.Context, data any) (any, error)
}

type BaseService struct {
}

// GetPage 获取分页数据
func (c *BaseService) GetPage(ctx *gin.Context) (pageSize, pageNum int) {
	var err error
	pageSize, err = strconv.Atoi(ctx.Query("pageSize"))
	if err != nil {
		pageSize = 10
	}
	pageNum, err = strconv.Atoi(ctx.Query("pageNum"))
	if err != nil {
		pageNum = 1
	}
	return
}

// GetLoginUser 获取登录用户
func (c *BaseService) GetLoginUser(ctx *gin.Context) (*model.User, error) {
	value, exists := ctx.Get(constant.ContextLoginUser)
	if !exists {
		return nil, errors.New("用户未登录")
	}
	user := value.(model.User)
	return &user, nil
}

// GetLoginUserId 获取登录用户ID
func (c *BaseService) GetLoginUserId(ctx *gin.Context) (int, error) {
	user, err := c.GetLoginUser(ctx)
	return user.Id, err
}
